<template>
	<view>
		<view class="user-section">
			<image src="/static/admin.png"></image>
			<!-- <image class="arc" src="/static/arc.png"></image> -->
		</view>

		<view class="user-info-box" @click="addressAction">
			<view class="headimgurl-item">
				<image class="headimgurl" :src="userInfo.headimgurl || '/static/missing-face.png'"></image>
				<text class="">{{ userInfo.name || '管理员1' }}</text>
			</view>
			<!-- <view class="portrait-box">
			<image class="portrait" :src="userInfo.headimgurl || '/static/missing-face.png'"></image>
		</view>
		<view class="info-box">
			<text class="username">{{ userInfo.name || '管理员1' }}</text>
		</view> -->
			<uni-text @click="addressAction" class="lg text-gray cuIcon-location"><span></span></uni-text>

			<view class="tj-sction">
				<!-- v-if="userInfo.name" -->
				<view class="grid col-2 grid-square" style="height: 40px">
					<view class="tj-item">
						<text class="title">剩余积分</text>
						<br />
						<!-- <text class="num">1000</text> -->
					</view>
					<view class="tj-item">
						<text class="title" style="color: red !important;">{{ totalNum }}</text>
						<br />
						<!-- <text class="num">{{totalNum}}</text> -->
					</view>
				</view>
			</view>
		</view>

		<view class="content">
			<view class="navbar" style="border-radius: 5px;">
				<view class="nav-item" :class="{ current: filterIndex === 0 }" @click="tabClick(0)">全部</view>
				<view class="nav-item" v-for="item in typeList" :key="item.id" :class="{ current: filterIndex === item.id }" @click="tabClick(item)">{{ item.name }}</view>
				<!-- <view class="nav-item" :class="{current: filterIndex === 2}" @click="tabClick(2)">
			 <text>-</text>
			 <view class="p-box">
			  <text :class="{active: priceOrder === 1 && filterIndex === 2}" class="yticon icon-shang"></text>
			  <text :class="{active: priceOrder === 2 && filterIndex === 2}" class="yticon icon-shang xia"></text>
			 </view>
			</view>
			<text class="cate-item yticon icon-fenlei1" @click="toggleCateMask('show')"></text> -->
			</view>
			<empty v-if="goodsList.length == 0" style="background: initial;top: 20%;"></empty>

			<view class="order-item" v-for="(item, index) in goodsList" :key="index">
				<view v-if="item.imgList.length === 1">
					<view class="goods-box-single">
						<image class="goods-img" :src="item.imgList[0].url" mode="aspectFill"></image>
						<view class="right">
							<text class="title clamp">
								<span>{{ item.spuName }}</span>
							</text>
							<text class="attr-box"><span>&nbsp;</span></text>
							<text class="price">
								共
								<text class="num" style="margin:0 8upx;">
									<span>{{ item.total }}</span>
								</text>
								件商品 实付积分
								<text class="price">
									<span style="margin:0 8upx;">{{ item.amount }} 积分</span>
								</text>
							</text>
						</view>
					</view>
				</view>
				<view v-else>
					<view class="listTitle">综合商品</view>
					<view class="flex">
						<view class="image">
							<block v-for="(val, index) in item.imgList.slice(0, 3)" :key="index"><image class="goods-img" :src="val.url" mode="aspectFill"></image></block>
							<view class="ellipsis" v-if="item.imgList.length > 3">...</view>
						</view>
						<view class="listShop">
							<view>
								实付
								<span class="num">{{ item.amount }}</span>
								积分
							</view>
							<view>
								共
								<span class="num">{{ item.total }}</span>
								件
							</view>
						</view>
					</view>
					<view></view>
				</view>
				<view class="action-box b-t">
					<text class="time">{{ item.createDate }}</text>
					<!-- <button v-if="item.status == 'YES'" class="action-btn">已兑换</button> -->
					<button @click="toggleSpec(item)" v-if="item.deliveryStatus == 'DFH'&&item.deliveryType== '1'" class="action-btn recom">福利码</button>
					<button @click="receiving(item)" v-if="item.deliveryStatus == 'DSH'&&item.deliveryType== '0'" class="action-btn recom">确认收货</button>
					<button @click="infoAction(item)" class="action-btn info">查看详情</button>
				</view>
			</view>
		</view>

		<!-- <view class="vip-card-box">
				<image class="card-bg" src="/static/vip-card-bg.png" mode=""></image>
				<view class="b-btn">
					立即开通
				</view>
				<view class="tit">
					<text class="yticon icon-iLinkapp-"></text>
					DCloud会员
				</view>
				<text class="e-m">DCloud Union</text>
				<text class="e-b">开通会员开发无bug 一测就上线</text>
			</view> -->
		<!-- <empty v-if="goodsList.length==0"></empty> -->
		<!-- <view class="i-top b-b">
        <text class="time"><span>2019-04-06 11:37</span></text>
        <text class="state" style="color: rgb(250, 67, 106);"><span>待付款</span></text>
      </view> -->

		<!-- <view
			class="cover-container"
			:style="[{
				transform: coverTransform,
				transition: coverTransition
			}]"
			@touchstart="coverTouchstart"
			@touchmove="coverTouchmove"
			@touchend="coverTouchend"
		> -->
		<!-- <image class="arc" src="/static/arc.png"></image> -->

		<!-- 订单 -->
		<!-- <view class="order-section">
				<view class="order-item" @click="navTo('/pages/order/order?state=0')" hover-class="common-hover"  :hover-stay-time="50">
					<text class="yticon icon-shouye"></text>
					<text>全部订单</text>
				</view>
				<view class="order-item" @click="goHref('https://shengst.tripln.top/subsidy/#/my-customer-service')" hover-class="common-hover"  :hover-stay-time="50">
					<text class="yticon icon-shouhoutuikuan"></text>
					<text>我的客服</text>
				</view>
				<view class="order-item" @click="navTo('/pages/order/order?state=1')"  hover-class="common-hover" :hover-stay-time="50">
					<text class="yticon icon-daifukuan"></text>
					<text>待付款</text>
				</view>
				<view class="order-item" @click="navTo('/pages/order/order?state=2')" hover-class="common-hover"  :hover-stay-time="50">
					<text class="yticon icon-yishouhuo"></text>
					<text>待收货</text>
				</view>
			</view> -->
		<!-- 浏览历史 -->
		<!-- <view class="history-section icon">
				<view class="sec-header">
					<text class="yticon icon-lishijilu"></text>
					<text>浏览历史</text>
				</view>
				<scroll-view scroll-x class="h-list">
					<image @click="navTo('/pages/product/product')" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1553105186633&di=c121a29beece4e14269948d990f9e720&imgtype=0&src=http%3A%2F%2Fimg004.hc360.cn%2Fm8%2FM04%2FDE%2FDE%2FwKhQplZ-QteEBvsbAAAAADUkobU751.jpg" mode="aspectFill"></image>
					<image @click="navTo('/pages/product/product')" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1553105231218&di=09534b9833b5243296630e6d5b728eff&imgtype=0&src=http%3A%2F%2Fimg002.hc360.cn%2Fm1%2FM05%2FD1%2FAC%2FwKhQcFQ3iN2EQTo8AAAAAHQU6_8355.jpg" mode="aspectFill"></image>
					<image @click="navTo('/pages/product/product')" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1553105320890&di=c743386be51f2c4c0fd4b75754d14f3c&imgtype=0&src=http%3A%2F%2Fimg007.hc360.cn%2Fhb%2FMTQ1OTg4ODY0MDA3Ny05OTQ4ODY1NDQ%3D.jpg" mode="aspectFill"></image>
					<image @click="navTo('/pages/product/product')" src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2691146630,2165926318&fm=26&gp=0.jpg" mode="aspectFill"></image>
					<image @click="navTo('/pages/product/product')" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1553105443324&di=8141bf13f3f208c61524d67f9bb83942&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01ac9a5548d29b0000019ae98e6d98.jpg" mode="aspectFill"></image>
					<image @click="navTo('/pages/product/product')" src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=191678693,2701202375&fm=26&gp=0.jpg" mode="aspectFill"></image>
				</scroll-view>
				<list-cell icon="icon-iconfontweixin" iconColor="#e07472" title="我的钱包" tips="您的会员还有3天过期"></list-cell>
				<list-cell icon="icon-dizhi" iconColor="#5fcda2" title="地址管理" @eventClick="navTo('/pages/address/address')"></list-cell>
				<list-cell icon="icon-share" iconColor="#9789f7" title="分享" tips="邀请好友赢10万大礼"></list-cell>
				<list-cell icon="icon-pinglun-copy" iconColor="#ee883b" title="晒单" tips="晒单抢红包"></list-cell>
				<list-cell icon="icon-shoucang_xuanzhongzhuangtai" iconColor="#54b4ef" title="我的收藏"></list-cell>
				<list-cell icon="icon-shezhi1" iconColor="#e07472" title="设置" border="" @eventClick="navTo('/pages/set/set')"></list-cell>
			</view> -->
		<!-- </view> -->
		<!-- 规格-模态层弹窗 -->
		<view class="popup spec" :class="specClass" @touchmove.stop.prevent="stopPrevent" @click="toggleSpec">
			<!-- 遮罩层 -->
			<view class="mask"></view>
			<view class="layer attr-content" @click.stop="stopPrevent">
				<view class="out-style">
					<view class="shop-outside">
						<view class="shop-info">
							<span>{{ qrCodeInfo.spuName }}</span>
							<!-- <span>￥</span>
								<span>123</span>
								<span>214</span> -->
						</view>
						<view class="code-div">
							<view class="qrcode-item"><canvas canvas-id="qrcode" style="margin: auto;width: 230px;height: 230px;border-radius: 5px;" /></view>
						</view>
						<view class="text-style"><span>请出示福利码进行核销</span></view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
import { selectUserIntegralById,updateDeliveryStatus, getOpenidMsg, selectUserIntegralReciveRecordList, updateVerification, selectUserIntegralReciveRecordById } from 'api/shop';
import listCell from '@/components/mix-list-cell';
import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
import empty from '@/components/empty';
import uQRCode from '@/js_sdk/Sansnn-uQRCode/uqrcode.js';
import Json from '@/Json';
import { mapState } from 'vuex';
let startY = 0,
	moveY = 0,
	pageAtTop = true;
export default {
	components: {
		uniLoadMore,
		empty,
		listCell
	},
	data() {
		return {
			filterIndex: 0,
			typeList: [
				{ id: '1', name: '待发货', value: 'DFH' }, 
				{ id: '2', name: '待收货', value: 'DSH' },
				{ id: '4', name: '待自提', value: 'DFH' },
				{ id: '3', name: '已完成', value: 'YWC' }],
			coverTransform: 'translateY(0px)',
			coverTransition: '0s',
			moving: false,
			totalNum: 0,
			surplus: 0,
			userInfo: {},
			buyInfo: [],
			formItem: {},
			shopList: [],
			shopId: '',
			goodsList: [],
			modalName: null,
			qrCodeInfo: {},
			dataList: [],
			specClass: 'none',
			specInfoClass: 'none',
			item: {},
			orderInfo: {},
			deliveryStatus: ''
		};
	},
	onShow() {
		// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
		let ua = window.navigator.userAgent.toLowerCase();
		// alert(JSON.stringify(ua))
		// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
		if (ua.match(/MicroMessenger/i) == 'micromessenger') {
			//是公众号
			console.log('是公众号');
			this.getOpenidMsgAction();
		} else {
			//不是公众号
			console.log('不是公众号');
		}

		console.log('我的');
		let categoryId = localStorage.getItem('categoryId');
		if (categoryId === '' || categoryId === undefined || categoryId === null) {
			this.contentShow = false;
			this.$api.msg('此链接有误，请重试');
			return false;
		}
	},
	// #ifndef MP
	onNavigationBarButtonTap(e) {
		const index = e.index;
		if (index === 0) {
			this.navTo('/pages/set/set');
		} else if (index === 1) {
			// #ifdef APP-PLUS
			const pages = getCurrentPages();
			const page = pages[pages.length - 1];
			const currentWebview = page.$getAppWebview();
			currentWebview.hideTitleNViewButtonRedDot({
				index
			});
			// #endif
			uni.navigateTo({
				url: '/pages/notice/notice'
			});
		}
	},
	// #endif
	//       computed: {
	// 	...mapState(['hasLogin','userInfo'])
	// },
	methods: {
		receiving(data){
			uni.showModal({
				content: '是否确认收货？',
				success: (e) => {
					if (e.confirm) {
						console.log('***',data)
						updateDeliveryStatus({batch:data.batch}).then(ret => {
							if (ret.data.errcode === 0) {
								this.$api.msg('收货成功！');
								// this.filterIndex = 0
								// this.deliveryStatus = '';
								this.init(this.userInfo.cardNo)
							} else {
								this.$api.msg(ret.data.errmsg);
								return false;
							}
						});
					}
				}
			})
		},
		tabClick(data) {
			if (data === 0) {
				this.deliveryStatus = '';
				this.filterIndex = data;
				this.init(this.userInfo.cardNo);
			} else {
				if(data.id == '4'){
					this.filterIndex = data.id;
					this.deliveryStatus = 'DFH';
					this.init(this.userInfo.cardNo);
				}else{
					this.filterIndex = data.id;
					this.deliveryStatus = data.value;
					this.init(this.userInfo.cardNo);
				}
			}
		},
		addressAction() {
			uni.navigateTo({
				url: `/pages/address/address`
			});
		},

		infoAction(item) {
			//测试数据没有写id，用title代替
			let id = item.batch;
			uni.navigateTo({
				url: `/pages/order/orderInfoJf?id=` + id
			});
		},
		toggleSpecInfo(data) {
			if (this.specInfoClass === 'show') {
				this.specInfoClass = 'hide';
				setTimeout(() => {
					this.specInfoClass = 'none';
				}, 250);
			} else if (this.specInfoClass === 'none') {
				this.specInfoClass = 'show';

				selectUserIntegralReciveRecordById({ batch: data.id }).then(ret => {
					if (ret.data.errcode === 0) {
						this.orderInfo = ret.data.data;
						this.orderInfo.imgurl = ret.data.data.imgList[0].url;
					} else {
						this.$api.msg(ret.data.errmsg);
						return false;
					}
				});
			}
		},
		//规格弹窗开关
		toggleSpec(data) {
			if (this.specClass === 'show') {
				this.specClass = 'hide';
				setTimeout(() => {
					this.specClass = 'none';
				}, 250);
			} else if (this.specClass === 'none') {
				this.specClass = 'show';
				this.qrcode(data);
			}
		},
		qrcode(data) {
			this.qrCodeInfo = data;

			uQRCode.make({
				canvasId: 'qrcode',
				componentInstance: this,
				text: 'jfjf:' + data.batch,
				size: 230,
				margin: 20,
				backgroundColor: '#ffffff',
				foregroundColor: '#000000',
				fileType: 'jpg',
				correctLevel: uQRCode.defaults.correctLevel,
				success: res => {
					// console.log(res)
				}
			});
		},
		//时间戳转换
		formatDate(date) {
			var date = new Date(date);
			var YY = date.getFullYear() + '-';
			var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
			var DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
			var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
			var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
			var ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
			return YY + MM + DD + ' ' + hh + mm + ss;
		},
		init(cardNo) {
			let data = {
				deliveryStatus: this.deliveryStatus, 
				idCard: cardNo, 
				brandId: localStorage.getItem('brandId') 
			}
			if(this.filterIndex == '1'||this.filterIndex == '2'){
				data.deliveryType='0'
			}
			if(this.filterIndex == '4'){
				data.deliveryType='1'
			}
			selectUserIntegralReciveRecordList(data).then(ret => {
				if (ret.data.errcode === 0) {
					this.goodsList = ret.data.data.result;
					for (var i = 0; i < this.goodsList.length; i++) {
						if (this.goodsList[i].createDate) {
							this.goodsList[i].createDate = this.formatDate(this.goodsList[i].createDate);
						}
					}
				} else {
					this.$api.msg(ret.data.errmsg);
					return false;
				}
			});
		},
		//取消订单
		cancelOrder(item) {
			uni.showLoading({
				title: '请稍后'
			});
			setTimeout(() => {
				let { stateTip, stateTipColor } = this.orderStateExp(9);
				item = Object.assign(item, {
					state: 9,
					stateTip,
					stateTipColor
				});

				//取消订单后删除待付款中该项
				let list = this.navList[1].orderList;
				let index = list.findIndex(val => val.id === item.id);
				index !== -1 && list.splice(index, 1);

				uni.hideLoading();
			}, 600);
		},

		//订单状态文字和颜色
		orderStateExp(state) {
			let stateTip = '',
				stateTipColor = '#fa436a';
			switch (+state) {
				case 1:
					stateTip = '待付款';
					break;
				case 2:
					stateTip = '待发货';
					break;
				case 9:
					stateTip = '订单已关闭';
					stateTipColor = '#909399';
					break;

				//更多自定义
			}
			return { stateTip, stateTipColor };
		},
		handle() {
			// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
			let ua = window.navigator.userAgent.toLowerCase();
			// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				//是微信浏览器
				window.location.href = this.$xeUtils.locat().origin + '/yq/#/handle-submit';
				// window.location.href = 'https://shengst.tripln.top/subsidy/#/city-card-handle';
			} else {
				window.location.href = 'https://shengst.tripln.top/subsidy/#/city-card-handle-app';
			}
		},
		getOpenidMsgAction() {
			getOpenidMsg().then(ret => {
				if (ret.data.errcode === 0) {
					let data = ret.data.data.result;
					if (data) {
						if (data.cardNo === null || data.cardNo === '' || data.cardNo === undefined) {
							this.handle();
						} else {
							this.userInfo = data;
							this.selectUserIntegralByIdAction(data.cardNo);
							this.init(data.cardNo);
						}
					} else {
						console.log('没有此人信息');
						this.handle();
					}
				} else if (ret.data.errcode === 9999 || ret.data.errcode === 9991) {
					this.handle();
				} else {
					this.$api.msg(ret.data.errmsg);
					return false;
				}
			});
		},
		selectUserIntegralByIdAction(idCard) {
			selectUserIntegralById({ idCard: idCard, type: '0', brandId: localStorage.getItem('brandId') }).then(ret => {
				if (ret.data.errcode === 0) {
					this.totalNum = ret.data.data.totalActivity;
					this.surplus = 1000 - ret.data.data.totalActivity;
					if (this.surplus < 0) {
						this.surplus = 0;
					}
				} else {
					this.$api.msg(ret.data.errmsg);
					return false;
				}
			});
		},

		/**
		 * 统一跳转接口,拦截未登录路由
		 * navigator标签现在默认没有转场动画，所以用view
		 */
		navTo(url) {
			if (!this.hasLogin) {
				url = '/pages/public/login';
			}
			uni.navigateTo({
				url
			});
		},

		/**
		 *  会员卡下拉和回弹
		 *  1.关闭bounce避免ios端下拉冲突
		 *  2.由于touchmove事件的缺陷（以前做小程序就遇到，比如20跳到40，h5反而好很多），下拉的时候会有掉帧的感觉
		 *    transition设置0.1秒延迟，让css来过渡这段空窗期
		 *  3.回弹效果可修改曲线值来调整效果，推荐一个好用的bezier生成工具 http://cubic-bezier.com/
		 */
		coverTouchstart(e) {
			if (pageAtTop === false) {
				return;
			}
			this.coverTransition = 'transform .1s linear';
			startY = e.touches[0].clientY;
		},
		coverTouchmove(e) {
			moveY = e.touches[0].clientY;
			let moveDistance = moveY - startY;
			if (moveDistance < 0) {
				this.moving = false;
				return;
			}
			this.moving = true;
			if (moveDistance >= 80 && moveDistance < 100) {
				moveDistance = 80;
			}

			if (moveDistance > 0 && moveDistance <= 80) {
				this.coverTransform = `translateY(${moveDistance}px)`;
			}
		},
		coverTouchend() {
			if (this.moving === false) {
				return;
			}
			this.moving = false;
			this.coverTransition = 'transform 0.3s cubic-bezier(.21,1.93,.53,.64)';
			this.coverTransform = 'translateY(0px)';
		}
	}
};
</script>

<style lang="scss" scoped>
@import './user.scss';
</style>
